import { Form, Input, Button, Card, message, Avatar, Select, Descriptions, Tag, Divider, Spin } from '@/utils/antd-imports';
import { UserOutlined } from '@/utils/icons';
import { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import employeeApi from '../api/employeeApi';

const { Option } = Select;

export default function PersonalSettings() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [employeeLoading, setEmployeeLoading] = useState(false);
  const [employeeData, setEmployeeData] = useState(null);
  const { user, updateUser } = useAuth();

  // 用户类型映射
  const getUserTypeText = (userType) => {
    const typeMap = {
      'user': '普通用户',
      'admin': '管理员',
      'super_admin': '超级管理员'
    };
    return typeMap[userType] || '未知';
  };

  // 用户类型颜色映射
  const getUserTypeColor = (userType) => {
    const colorMap = {
      'user': 'blue',
      'admin': 'green',
      'super_admin': 'red'
    };
    return colorMap[userType] || 'default';
  };

  // 获取员工信息
  useEffect(() => {
    const loadEmployeeInfo = async () => {
      // 如果有员工ID，从员工API获取详细信息
      if (user?.employeeId) {
        setEmployeeLoading(true);
        try {
          const response = await employeeApi.getEmployeeDetail(user.employeeId);
          if (response.code === 200) {
            const employee = response.data;
            setEmployeeData(employee);
            
            // 使用员工信息填充表单
            form.setFieldsValue({
              name: employee.name || user.username,
              email: employee.email || user.email,
              phone: employee.phone || user.phone,
              department: employee.department || '未知',
              position: employee.position || '未知'
            });
          }
        } catch (error) {
          console.error('加载员工信息失败:', error);
          // 如果加载失败，使用基础信息
          form.setFieldsValue({
            name: user.username || '管理员',
            email: user.email || '',
            phone: user.phone || '',
            department: '未知',
            position: '未知'
          });
        } finally {
          setEmployeeLoading(false);
        }
      } else {
        // 没有员工ID，使用基础用户信息
        form.setFieldsValue({
          name: user.username || '管理员',
          email: user.email || '',
          phone: user.phone || '',
          department: '管理层',
          position: '管理员'
        });
      }
    };

    if (user) {
      loadEmployeeInfo();
    }
  }, [user, form]);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      // 如果绑定了员工，更新员工信息
      if (user?.employeeId && employeeData) {
        const updateData = {
          id: user.employeeId,
          name: values.name,
          email: values.email,
          phone: values.phone
          // 不传递 department 和 position，因为这些字段只能由管理员修改
        };
        
        await employeeApi.updateEmployee(updateData);
        
        // 重新加载员工信息
        const response = await employeeApi.getEmployeeDetail(user.employeeId);
        if (response.code === 200) {
          setEmployeeData(response.data);
        }
      }
      
      // 更新用户信息到上下文
      updateUser({
        email: values.email,
        phone: values.phone
      });
      
      message.success('个人信息更新成功');
    } catch (error) {
      console.error('更新失败:', error);
      message.error('更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <Card title="个人设置" bordered={false}>
        {/* 登录信息展示区域 */}
        <Card 
          title="登录信息" 
          size="small" 
          style={{ marginBottom: 24, backgroundColor: '#fafafa' }}
        >
          <Spin spinning={employeeLoading}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
              <Avatar 
                size={64} 
                style={{ 
                  backgroundColor: '#1890ff',
                  fontSize: '24px',
                  fontWeight: 'bold',
                  marginRight: 16
                }}
              >
                {employeeData?.name ? employeeData.name.charAt(0).toUpperCase() : (user?.username ? user.username.charAt(0).toUpperCase() : 'U')}
              </Avatar>
              <div>
                <h3 style={{ margin: 0, marginBottom: 8 }}>
                  {employeeData?.name || user?.username || '管理员'}
                </h3>
                <Tag color={getUserTypeColor(user?.userType)}>
                  {getUserTypeText(user?.userType)}
                </Tag>
              </div>
            </div>
            
            <Descriptions size="small" column={2}>
              <Descriptions.Item label="姓名">
                {employeeData?.name || user?.username || '未知'}
              </Descriptions.Item>
              <Descriptions.Item label="用户名">
                {user?.username || 'admin'}
              </Descriptions.Item>
              <Descriptions.Item label="部门">
                {employeeData?.department || '未知'}
              </Descriptions.Item>
              <Descriptions.Item label="岗位">
                {employeeData?.position || '未知'}
              </Descriptions.Item>
              <Descriptions.Item label="用户类型">
                <Tag color={getUserTypeColor(user?.userType)}>
                  {getUserTypeText(user?.userType)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="登录状态">
                <Tag color="green">已登录</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="员工编号">
                {employeeData?.employeeCode || '未绑定员工'}
              </Descriptions.Item>
              <Descriptions.Item label="Token状态">
                <Tag color={user?.token ? "green" : "red"}>
                  {user?.token ? "有效" : "无效"}
                </Tag>
              </Descriptions.Item>
            </Descriptions>
          </Spin>
        </Card>

        <Divider />

        {/* 个人信息编辑区域 */}
        <Card title="个人信息编辑" size="small">
          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
          >
            <Form.Item
              label="姓名"
              name="name"
              rules={[{ required: true, message: '请输入您的姓名' }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
            
            <Form.Item
              label="电子邮箱"
              name="email"
              rules={[
                { required: true, message: '请输入您的邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input placeholder="请输入邮箱" />
            </Form.Item>
            
            <Form.Item
              label="手机号码"
              name="phone"
              rules={[
                { required: true, message: '请输入您的手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
            
            <Form.Item
              label="所属部门"
              name="department"
              tooltip="所属部门信息由管理员维护，个人无法修改"
            >
              <Input placeholder="请输入部门" disabled />
            </Form.Item>
            
            <Form.Item
              label="岗位"
              name="position"
              tooltip="岗位信息由管理员维护，个人无法修改"
            >
              <Input placeholder="请输入岗位" disabled />
            </Form.Item>
            
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading}>
                保存设置
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </Card>
    </div>
  );
}